package cn.iocoder.springboot.lab04.rabbitmqdemo.config;

import cn.iocoder.springboot.lab04.rabbitmqdemo.message.Demo05Message;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.batch.BatchingStrategy;
import org.springframework.amqp.rabbit.batch.SimpleBatchingStrategy;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.BatchingRabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;

@Configuration
public class RabbitConfig {

    public static class DirectExchangeDemoConfiguration {
        @Bean
        public Queue demo05Queue() {
            return new Queue(Demo05Message.QUEUE, true, false, false);
        }

        @Bean
        public DirectExchange demo05Exchange() {
            return new DirectExchange(Demo05Message.EXCHANGE, true, false);
        }

        @Bean
        public Binding demo05Binding() {
            return BindingBuilder.bind(demo05Queue()).to(demo05Exchange()).with(Demo05Message.ROUTING_KEY);
        }

        @Bean
        public BatchingRabbitTemplate batchingRabbitTemplate(ConnectionFactory connectionFactory) {
            // 创建 BatchingStrategy 对象，代表批量策略
            int batchSize = 16384;
            int bufferLimit = 33554432;
            int timeout = 30000;
            BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(batchSize, bufferLimit, timeout);

            // 创建 TaskScheduler 对象，用于实现超时发送的定时器
            TaskScheduler taskScheduler = new ConcurrentTaskScheduler();

            // 创建 BatchingRabbitTemplate 对象
            BatchingRabbitTemplate batchingRabbitTemplate = new BatchingRabbitTemplate(batchingStrategy, taskScheduler);
            batchingRabbitTemplate.setConnectionFactory(connectionFactory);
            return batchingRabbitTemplate;
        }
    }
}
